import { useEditorStore } from '@/stores/editor'
import { useGlobalStore } from '@/stores/global'
import { ElMessageBox } from 'element-plus'
import type { Action } from 'element-plus'

// 在 Editor 中完成保存作品的一系列相关功能
// disableSideEffects 控制启用其他副作用功能 默认启用（还有一种方式，就是把副作用功能用函数包裹起来，返回出去，需要使用地方再调用）
export default function useSaveWork(disableSideEffects = false) {
  const route = useRoute()
  const editor = useEditorStore()
  const global = useGlobalStore()

  const saveIsLoading = computed(() => global.isOpLoading('saveWork'))
  const isDirty = computed(() => editor.isDirty)
  const components = computed(() => editor.components)
  const page = computed(() => editor.page)

  const currentWorkId = route.params.id as string

  // 保存作品
  const saveWork = async () => {
    const { title, props, coverImg, desc, setting } = page.value
    const payload = {
      title,
      coverImg,
      desc,
      content: {
        components: components.value,
        props,
        setting
      }
    }
    await editor.saveWork(currentWorkId, payload)
  }

  if (!disableSideEffects) {
    // 自动保存
    let timer = null
    onMounted(() => {
      timer = setInterval(() => {
        if (isDirty.value) {
          saveWork()
        }
      }, 10000 * 5)
    })

    onUnmounted(() => {
      clearInterval(timer)
    })

    // 离开路由前提示
    onBeforeRouteLeave((to, from, next) => {
      if (isDirty.value) {
        ElMessageBox.confirm('作品还未保存，是否保存？', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '不保存',
          callback: async (action: Action) => {
            if (action === 'confirm') {
              await saveWork()
              next()
            } else {
              next()
            }
          }
        })
      } else {
        next()
      }
    })
  }

  return {
    saveWork,
    saveIsLoading
  }
}
